{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aed9cdc2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "程序异常退出: asyncio.run() cannot be called from a running event loop\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\cheng.chen\\AppData\\Local\\Temp\\ipykernel_3276\\2298910914.py:69: RuntimeWarning: coroutine 'main' was never awaited\n",
      "  print(f\"程序异常退出: {e}\")\n",
      "RuntimeWarning: Enable tracemalloc to get the object allocation traceback\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import logging\n",
    "\n",
    "# 配置日志\n",
    "logging.basicConfig(level=logging.INFO)\n",
    "logger = logging.getLogger(__name__)\n",
    "\n",
    "async def setup():\n",
    "    \"\"\"初始化设置\"\"\"\n",
    "    logger.info(\"程序初始化\")\n",
    "    await asyncio.sleep(0.1)  # 模拟初始化\n",
    "\n",
    "async def do_work():\n",
    "    \"\"\"主要业务logic\"\"\"\n",
    "    logger.info(\"开始工作\")\n",
    "    \n",
    "    # 并发执行多个任务\n",
    "    tasks = [\n",
    "        asyncio.create_task(task_1()),\n",
    "        asyncio.create_task(task_2()),\n",
    "        asyncio.create_task(task_3())\n",
    "    ]\n",
    "    \n",
    "    results = await asyncio.gather(*tasks)\n",
    "    return results\n",
    "\n",
    "async def task_1():\n",
    "    await asyncio.sleep(1)\n",
    "    return \"任务1完成\"\n",
    "\n",
    "async def task_2():\n",
    "    await asyncio.sleep(2)\n",
    "    return \"任务2完成\"\n",
    "\n",
    "async def task_3():\n",
    "    await asyncio.sleep(1.5)\n",
    "    return \"任务3完成\"\n",
    "\n",
    "async def cleanup():\n",
    "    \"\"\"清理资源\"\"\"\n",
    "    logger.info(\"程序清理\")\n",
    "    await asyncio.sleep(0.1)\n",
    "\n",
    "async def main():\n",
    "    \"\"\"主函数\"\"\"\n",
    "    try:\n",
    "        await setup()\n",
    "        results = await do_work()\n",
    "        \n",
    "        for result in results:\n",
    "            logger.info(f\"结果: {result}\")\n",
    "            \n",
    "        return \"程序成功完成\"\n",
    "        \n",
    "    except Exception as e:\n",
    "        logger.error(f\"程序出错: {e}\")\n",
    "        raise\n",
    "    finally:\n",
    "        await cleanup()\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # 程序入口点\n",
    "    try:\n",
    "        final_result = asyncio.run(main())\n",
    "        print(f\"最终结果: {final_result}\")\n",
    "    except KeyboardInterrupt:\n",
    "        print(\"程序被用户中断\")\n",
    "    except Exception as e:\n",
    "        print(f\"程序异常退出: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ed34913",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c526932d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello A\n",
      "Hello B\n",
      "World A\n",
      "World B\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "async def say_hello(name):\n",
    "    print(f\"Hello {name}\")\n",
    "    await asyncio.sleep(1)\n",
    "    # time.sleep(2)\n",
    "    print(f\"World {name}\")\n",
    "\n",
    "async def main():\n",
    "    await asyncio.gather(say_hello('A'), say_hello('B'))\n",
    "\n",
    "await main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a37a5357",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "from colorama import init, Fore, Style\n",
    "\n",
    "init(autoreset=True)\n",
    "\n",
    "# 配置日志记录器\n",
    "logger = logging.getLogger(__name__)\n",
    "logging.basicConfig(level=logging.INFO)\n",
    "\n",
    "def example_callback(host_name):\n",
    "    display_line = \"This is an example log message.\"\n",
    "    colors = [Fore.BLUE, Fore.GREEN, Fore.YELLOW, Fore.MAGENTA, Fore.CYAN]\n",
    "    color_index = hash(host_name) % len(colors)\n",
    "    color = colors[color_index]\n",
    "    logger.info(f\"{color}[{host_name}]{Style.RESET_ALL} | {display_line}\")\n",
    "\n",
    "# 测试调用\n",
    "example_callback(\"personal-server-2\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
